package com.example.day12_br;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.NotificationTarget;

/**
 * 广播接收者
 * 注册：
 * 1.创建一个类继承自BroadcastReceiver
 * 2.重写onReceive方法，对各个频道道后进行响应处理
 * 3.在清单文件中添加receiver标签 添加频道号（安卓8.0以后不支持）
 * (3.动态)在对应界面实例化关播接受者，设置接收的频道号，注册广播接受者
 * 4.发送广播对应的频道号
 *
 * 系统广播：不需要我们去发送广播
 * 只需要在广播接收者注册中添加对应的频道号，同时重写onReceive中关于频道号的状态的处理
 *
 * 广播+通知结合
 * 通知上的点击事件   相当于发送广播
 * 需要在广播接收者注册中添加对应的频道号，同时重写onReceive中关于频道号的状态的处理
 *
 */

public class MainActivity extends AppCompatActivity {
    JingReceiver receiver;
    Jing2Receiver receiver2;
    LocalReceiver localReceiver;
    LocalBroadcastManager manager;
    private ImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        requestPermissions(new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.WRITE_CONTACTS,
                Manifest.permission.READ_SMS,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.WRITE_CALL_LOG,
                Manifest.permission.READ_CALL_LOG

        }, 100);
        {
            receiver = new JingReceiver();
            IntentFilter filter = new IntentFilter();
            filter.setPriority(10);//优先级0-1000，数字越大，优先级越高
            filter.addAction("com.bw.2208");
            registerReceiver(receiver, filter);//注册关播接收者
        }
        {
            receiver2 = new Jing2Receiver();
            IntentFilter filter = new IntentFilter();
            filter.setPriority(100);
            filter.addAction("com.bw.2208");
            filter.addAction("com.bw.2209");
            filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            filter.addAction("android.intent.action.PHONE_STATE");
            filter.addAction("android.intent.action.AIRPLANE_MODE");
            filter.addAction("android.intent.action.HEADSET_PLUG");
            filter.addAction("com.bw.pre");//通知上图片的频道号
            filter.addAction("com.bw.play");//通知上图片的频道号
            filter.addAction("com.bw.next");//通知上图片的频道号
            filter.addAction("com.bw.change");//变更头像的频道号
            registerReceiver(receiver2, filter);
        }
        {
            localReceiver = new LocalReceiver();
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction("com.bw.2208");
            manager = LocalBroadcastManager.getInstance(this);
            manager.registerReceiver(localReceiver, intentFilter);
        }



    }

    public void send(View view) {
        Intent intent = new Intent();
        intent.setAction("com.bw.2208");
        //sendBroadcast(intent);//发送普通广播---无序广播，设置了优先级也没用
        //sendOrderedBroadcast(intent,null);//发送有序广播，若未设置优先级，和普通广播相同
        //sendStickyBroadcast(intent);//发送粘性广播：无论接受者所在的app是否启动，只要启动就能接受   普通广播：接收者所在的APP必须启动才能接收
        manager.sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);//解除注册关播接收者
        unregisterReceiver(receiver2);
        manager.unregisterReceiver(localReceiver);
    }

    @SuppressLint("RemoteViewLayout")
    public void sendNoti(View view) {
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        RemoteViews views = new RemoteViews(getPackageName(), R.layout.noti_diy);
        views.setTextViewText(R.id.tv, "张三之歌");//更改文字
        //点击通知上的按钮   发出广播
        {
            Intent intent = new Intent();
            intent.setAction("com.bw.pre");
            PendingIntent broadcast = PendingIntent.getBroadcast(this, 103, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.pre, broadcast);
        }
        {
            Intent intent = new Intent();
            intent.setAction("com.bw.play");
            PendingIntent broadcast = PendingIntent.getBroadcast(this, 104, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.play, broadcast);
        }
        {
            Intent intent = new Intent();
            intent.setAction("com.bw.next");
            PendingIntent broadcast = PendingIntent.getBroadcast(this, 105, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            views.setOnClickPendingIntent(R.id.next, broadcast);
        }

        //点击跳转
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 102, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification.Builder builder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCustomContentView(views)
                .setContentIntent(pendingIntent);
        //版本控制
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationManager.createNotificationChannel(new NotificationChannel("id", "name", NotificationManager.IMPORTANCE_DEFAULT));
            builder.setChannelId("id");
        }
        Notification notification = builder.build();
        notificationManager.notify(1, notification);
        NotificationTarget target = new NotificationTarget(this, R.id.iv, views, notification, 1);
        Glide.with(this)
                .asBitmap()
                .load("http://10.161.9.80:8080/res/music/image/36024806.jpg")
                .into(target);
    }

    public void change(View view) {
        //发送广播
        Intent intent = new Intent();
        intent.setAction("com.bw.change");
        sendBroadcast(intent);
    }

    private void initView() {
        iv = (ImageView) findViewById(R.id.iv);
    }


    class Jing2Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.bw.2208".equals(intent.getAction())) {
                Log.d("sss", "onReceive:Jing2Receiver接收到了广播 ");
                //abortBroadcast();//中断广播
            } else if ("com.bw.2209".equals(intent.getAction())) {
                Log.d("sss", "onReceive: Jing2Receiver接收到了广播2209");
            } else if ("android.intent.action.HEADSET_PLUG".equals(intent.getAction())) {//插拔耳机的系统广播
                int state = intent.getExtras().getInt("state");
                if (state == 1) {
                    Log.d("sss", "onReceive: 您插入了耳机");
                } else if (state == 0) {
                    Log.d("sss", "onReceive: 您拔出了耳机");
                }
            } else if ("android.intent.action.AIRPLANE_MODE".equals(intent.getAction())) {//飞行模式的系统广播
                boolean state = intent.getExtras().getBoolean("state");
                if (state) {
                    Log.d("sss", "onReceive: 您开启了飞行模式");
                } else {
                    Log.d("sss", "onReceive: 您关闭了飞行模式");
                }
            } else if ("android.intent.action.PHONE_STATE".equals(intent.getAction())) {//来电状态的广播
                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
                int state = telephonyManager.getCallState();
                if (state == TelephonyManager.CALL_STATE_RINGING) {
                    Log.d("sss", "onReceive: 您的手机正在来电中");
                } else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
                    Log.d("sss", "onReceive: 您的手机正在通话中");
                } else if (state == TelephonyManager.CALL_STATE_IDLE) {
                    Log.d("sss", "onReceive: 您的手机通话已挂断");
                }
            } else if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo info = connectivityManager.getActiveNetworkInfo();//获取活跃的网络信息
                if (info != null && info.isConnected()) {
                    Log.d("sss", "onReceive: 当前网络是畅通的");
                } else {
                    Log.d("sss", "onReceive: 当前没有网");
                }
            } else if ("com.bw.pre".equals(intent.getAction())) {
                Log.d("sss", "onReceive: 点击了通知上的上一首的图片");
            } else if ("com.bw.play".equals(intent.getAction())) {
                Log.d("sss", "onReceive: 点击了通知上的播放或暂停的图片");
            } else if ("com.bw.next".equals(intent.getAction())) {
                Log.d("sss", "onReceive: 点击了通知上的下一首的图片");
            } else if ("com.bw.change".equals(intent.getAction())) {
                Glide.with(MainActivity.this).load("http://10.161.9.80:8080/res/music/image/36024806.jpg")
                        .into(iv);
            }
        }
    }

    class LocalReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if ("com.bw.2208".equals(intent.getAction())) {
                Log.d("sss", "onReceive: 本地广播接收者接收到了本地广播");
            }
        }
    }
}